package com.shudingke.controller;


import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;


import com.shudingke.domain.*;
import com.shudingke.domain.vo.CartVo;
import com.shudingke.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2022-06-29
 */
@Controller
@RequestMapping("/orders")
public class OrderController {
    @Autowired
    ICartService service;
    //前往订单页面
    //把选中的订单做好标记
    @RequestMapping("/orderConfirm")
    @ResponseBody
    public String orderConfirm(HttpServletRequest req,String[] boxs){
       // System.out.println(Arrays.toString(boxs));
        String uuid = req.getSession().getAttribute("uid").toString();
        Cart cart = new Cart();
        List<CartVo> carts = service.findAll(Integer.parseInt(uuid),null);
        List<CartVo> list = new ArrayList<>();
        for (int i = 0; i < boxs.length; i++){
            if ("true".equals(boxs[i])){
                list.add(carts.get(i));
            }
        }
        //把选中的商品存到session域中
        req.getSession().setAttribute("payList",list);
        return "111";
    }
    
    //订单页面加载数据
    @RequestMapping("/load")
    @ResponseBody
    public Map load(HttpServletRequest req){
        Map map = new HashMap();
        //获取收货列表信息
        String uuid = req.getSession().getAttribute("uid").toString();
        Address address = new Address();
        QueryWrapper<Address> qw = new QueryWrapper<>();
        qw.eq("uid",Integer.parseInt(uuid));
        List<Address> addressList = address.selectList(qw);
        map.put("addressList",addressList);
        
        //取出session域中的要结算的商品
        List<CartVo> list = (List<CartVo>) req.getSession().getAttribute("payList");
        map.put("goodsList",list);

        int nums = 0;
        double sum = 0;
        for (CartVo cartVo : list) {
            nums += cartVo.getNum();
            sum += cartVo.getNum() * cartVo.getPrice();
        }
        map.put("nums",nums);
        map.put("sum",sum);
        return map;
    }
    
    //前往结算界面
    @RequestMapping("/gotoOrderConfirm")
    public String gotoOrderConfirm(){
        return "orderConfirm";
    }


    //在线支付后创建订单
    //每个订单项目可能包含多个订单  所有id不是唯一的
    //每个订单是一种产品，id唯一非空自增
    @RequestMapping("/createOrder")
    @ResponseBody
    public String createOrder(HttpServletRequest req,String address){
        //获取当前时间的秒以及毫秒
        String format = new SimpleDateFormat("ssSSS").format(new Date());

        String uuid = req.getSession().getAttribute("uid").toString();

        if (StringUtils.isEmpty(address)){
            return "400";
        }else {
            //获取要购买的商品的信息
            List<CartVo> list = (List<CartVo>) req.getSession().getAttribute("payList");
            int cids[] = new int[list.size()];
            for (int i = 0; i < list.size(); i++) {
                cids[i] = list.get(i).getCid();
            }
            
            
            
            
            String[] split = address.split("\\b\\b\\b");
            Address address1 = new Address();
            QueryWrapper<Address> qw = new QueryWrapper<>();
            qw.eq("name",split[0]).eq("tag",split[2])
                    .eq("address",split[4]).eq("phone",split[6]);
            Address one = address1.selectOne(qw);
            
            
            
            for (int i = 0; i < cids.length; i++){
                Cart cart = new Cart();
                cart.setCid(cids[i]);
                Cart cart1 = cart.selectById();

                Orders orders = new Orders();
                orders.setUid(Integer.parseInt(uuid));
                orders.setRecvName(one.getName());
                orders.setRecvPhone(one.getPhone());
                orders.setRecvProvince(one.getProvinceName());
                orders.setRecvCity(one.getCityName());
                orders.setRecvArea(one.getAreaName());
                orders.setRecvAddress(one.getAddress());
                orders.setTotalPrice(cart1.getNum() * cart1.getPrice());
                orders.setStatus("已支付");
                orders.setOrderTime(LocalDateTime.now());
                orders.setPayTime(LocalDateTime.now());
                
                orders.insert();

                Orderitem orderitem = new Orderitem();
                QueryWrapper<Orders> qw1 = new QueryWrapper<>();
                qw1.eq("uid", orders.getUid());
                qw1.eq("orderTime", orders.getOrderTime());
                List<Orders> ordersList = orders.selectList(qw1);
                orderitem.setOid(ordersList.get(ordersList.size() - 1).getOid());
                orderitem.setPid(cart1.getPid());


                Products products = new Products();
                products.setId(cart1.getPid());
                Products products1 = products.selectById();
                orderitem.setTitle(products1.getTitle());
                orderitem.setImage(products1.getImage());
                orderitem.setPrice(cart1.getPrice());
                orderitem.setNum(cart1.getNum());
                orderitem.setId(Integer.parseInt(uuid + format));
                orderitem.insert();
                
                //把这个订单项目的id存储到session域中
                req.getSession().setAttribute("itemId",orderitem.getId());
            }
            
            return "200";    
        }
        
        
        
        
    }
    
    

    //前往结算界面2
    @RequestMapping("/gotoPayment")
    public String gotoPayment(){
        return "payment";
    }
    
    
    //加载订单页面
    @RequestMapping("/ordersLoad")
    @ResponseBody
    public List<Map> ordersLoad(HttpServletRequest req){
        List<Map> list = new ArrayList<>();

        String uuid = req.getSession().getAttribute("uid").toString();

        Orders orders = new Orders();
        QueryWrapper<Orders> qw = new QueryWrapper<>();
        qw.eq("uid",Integer.parseInt(uuid));
        List<Orders> ordersList = orders.selectList(qw);
        
        //去重取出所有订单编号
        Set<Integer> set = new HashSet();
        for (Orders orders1 : ordersList) {
            Orderitem orderitem = new Orderitem();
            QueryWrapper<Orderitem> qw1 = new QueryWrapper<>();
            qw1.eq("oid",orders1.getOid());
            Orderitem orderitem1 = orderitem.selectOne(qw1);
            set.add(orderitem1.getId());
        }
        
        
        //再遍历一边存进map
        for (int id : set) {
            Map map = new HashMap();
            List<Orderitem> list1 = new ArrayList<>();
            for (Orders orders1 : ordersList) {
                Orderitem orderitem = new Orderitem();
                QueryWrapper<Orderitem> qw1 = new QueryWrapper<>();
                qw1.eq("oid",orders1.getOid());
                Orderitem orderitem1 = orderitem.selectOne(qw1);
                if (orderitem1.getId() == id){
                    list1.add(orderitem1);
                    map.put("recvName",orders1.getRecvName());

                    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
                    map.put("payTime",dtf.format(orders1.getPayTime()));
                }
            }
            map.put("id",id);
            map.put("orderList",list1);
            list.add(map);
        }
        return list;
    }
    
    
    
    //前往订单详情界面
    @RequestMapping("/toOrderInfo")
    public String toOrderInfo(Model model,String id,String oid){
        Orders orders = new Orders();
        orders.setOid(Integer.parseInt(oid));
        Orders byId = orders.selectById();
        
        Orderitem orderitem = new Orderitem();
        QueryWrapper<Orderitem> qw = new QueryWrapper<>();
        qw.eq("oid",Integer.parseInt(oid));
        Orderitem one = orderitem.selectOne(qw);
        
        model.addAttribute("orders",byId);
        model.addAttribute("orderItem",one);
        
        
        return "orderInfo";
    }
}